﻿using UnityEngine;
using UnityEngine.SceneManagement;

namespace Core
{
    public abstract class AbstractScene : Core.Entity, IScene, IAwake<int>
    {
        public TblScene.Conf Conf { get; private set; }

        protected SequencePU nodes;

        public virtual void Awake(int id)
        {
            var tbl = G.Table.GetSO<TblScene>();
            Conf = tbl.Find(id);
            if (Conf == null)
            {
                throw new System.Exception($"Error! Scene Conf Is Null, id={id}");
            }

            nodes = Create<SequencePU, string>(GetType().Name);
        }

        public void Enter()
        {
            OnEnter();

            nodes.Start();
        }

        public virtual void Update()
        {
            if (nodes.IsComplete) return;

            nodes.Update();
            if (nodes.IsComplete)
            {
                nodes.Finish();
                OnEnterComplete();
            }
        }

        public void Exit()
        {
            OnExit();
        }

        protected virtual void OnEnter() { }
        protected virtual void OnEnterComplete() { }
        protected virtual void OnExit() { }

        public readonly string MetaScene = "MetaScene";

        public bool CheckMetaSceneIsLoaded()
        {
            for (var i = 0; i < SceneManager.sceneCount; i++)
            {
                var scene = SceneManager.GetSceneAt(i);
                if (scene.name == MetaScene)
                {
                    return true;
                }
            }

            return false;
        }

        public void MoveGoToMetaScene(GameObject go)
        {
            for (var i = 0; i < SceneManager.sceneCount; i++)
            {
                var scene = SceneManager.GetSceneAt(i);
                if (scene.name == MetaScene)
                {
                    SceneManager.MoveGameObjectToScene(go, scene);
                }
            }
        }
    }
}